<template>
  <div class="mainn">
    <div class="ddfd">
    <div class="ddTitles"
         :class="[(status === 0 ? 'stayBg' :
         (status === 1 ? 'runBg' : (status === 2 || status  === 3 ? 'errorBg' : 'defaultBg')))]">
      <div class="dxxxs">
        <H2>{{data.name? data.name : '未选择'}}</H2>
      </div>
      <div class="dxxxsy">
        <Button type="primary" long size="small" @click.native="doAll(status == 0 ? 1 : 0)" :disabled="requestStatus
        || !data.name || see || status === 2 || status === 3" >{{status == 0 ? '一键启动' : '一键关闭'}}</Button>
      </div>
    </div>
    <div class="chainn">
      <div style="width: 100%;">
        <div v-for="(item, index) in showProcesses" :key="index" :style="{'float': 'left', 'width': index === showProcesses.length - 1 ? '' : '28%'}">
          <BallStatus :data="item" :if-last="index == showProcesses.length-1" :statuses="sonStutus" ref="sons" @dot-use-btn="dotDisabledBtn"
                      @do-use-btn="doDisabledBtn" :if-ctrl="status === 0 || status === 1"
                      @lock-other-sons="lockOtherSons(index)" @release-all-sons="releaseAllSons()"></BallStatus>
        </div>
      </div>
    </div>
    <Spin size="large" v-if="loading" fix></Spin>
    </div>
  </div>
</template>

<script>
  import BallStatus from './BallStatus'
  export default {
    name: 'RunChain',
    components: {BallStatus},
    props: {
        see: {
            type: Boolean,
            default () {
                return false
            }
        }
    },
    mounted: function () {
    },
    data () {
      return {
        data: {},
        originalSendData: {},
        status: 999, // 0 待机 1 运行 2 故障 3 通讯不上
        requestStatus: false,
        loading: false,
        showProcesses: [],
        sonStutus: []
      }
    },
    methods: {
      doAll (run) {
        this.$Modal.confirm({
          title: '操作确认',
          content: '<p>确认要执行远程操作设备指令吗？</p>',
          onOk: () => {
            this.requestStatus = true
            this.callSon(0, run)
          },
          onCancel: () => {
          }
        })
      },
      lockOtherSons (curIndex) {
        // 禁止点击其他的节点
        for (let i = 0; i < this.$refs.sons.length; i++) {
          if (i !== curIndex) {
            this.$refs.sons[i].lock = true
          }
        }
      },
      releaseAllSons () {
        for (let i = 0; i < this.$refs.sons.length; i++) {
            this.$refs.sons[i].lock = false
        }
      },
      checkSonsStatus() {
        // 检测子节点的状态，全部统一与否，决定 一键操作 button的状态
        let allStatus = true
        for (let i = 0; i < this.$refs.sons.length; i++) {
          // 必须跟一键启动/关闭 互斥，有相同，则是有操作不成功
          if (this.$refs.sons[i].status === this.status) {
            allStatus = false
            break
          }
        }
        return allStatus
      },
      callSon (id, type) {
        this.lockOtherSons(id)
        this.$refs.sons[id].fatherCtrl(type).then(resp => {
          // 返回操作点的操作结果 1 为操作成功的提示 2 为操作异常的提示
          this.$Notice.info({
            title: '提示',
            desc: resp.msg
          })
          if (resp) {
            id++
            if (id < this.showProcesses.length) {
              // 如果还有 操作点，继续请求
              this.callSon(id, type)
            } else {
              // 如果处理最后一个操作点，则处理 当前的 一键操作 状态
              if (this.checkSonsStatus()) {
                this.status = this.status === 0 ? 1 : 0
                // 调转显示的数据顺序 --> 直接模拟其他组件发送数据到这里来
                this.feedMe(this.originalSendData)
              }
              this.requestStatus = false
            }
          }
        }).finally(() => {
          // 放开禁止点击其他点
          this.releaseAllSons()
        })
      },
      doDisabledBtn () {
        this.requestStatus = false
      },
      dotDisabledBtn () {
        this.requestStatus = true
      },
        loadMainDevStatus () {
        this.loading = true
            window.myapi.do_post('iot/dev/sysReal', { uuid: this.data.uuid }).then(resp => {
                if (resp.status === 200 && resp.data.status === 200) {
                    this.sonStutus = resp.data.data
                    this.handleStatusDatas(resp.data.data)
                }
            }).finally(() => {
              this.loading = false
            })
        },
       handleStatusDatas (original) {
          // 处理主机状态
          let runItem = original.find(item => item.keyName === '运行状态')
          let bengStatus = original.find(item => item.keyName === '水泵运行')
          let errorItem = original.find(item => item.keyName === '故障状态')
           if (errorItem && errorItem.value === 1) {
               this.status = 2
           } else {
               if (runItem) {
                   if (runItem.value === 'N/A') {
                       this.status = 3
                   } else {
                    this.status = runItem.value
                   }
               }
               // 冷却泵的状态
               if (bengStatus) {
                   if (bengStatus.value === 'N/A') {
                       this.status = 3
                   } else {
                    this.status = bengStatus.value
                   }
               }
           }
           // 处理顺序
         this.handlerShowOrder()
        },
      handlerShowOrder () {
        // 判断 显示的顺序  开机，先开气阀，再开主机。关机，调转
        if (this.status === 1) {
          // 主机开机状态，只能执行 关闭。关主机->关气阀水阀
          this.showProcesses = this.data.processes
        } else {
          // 反序；；
          this.showProcesses = this.data.processes.reverse()
        }
      },
      feedMe (obj) {
        // 先解开 一键操作 的权限
        this.doDisabledBtn()
        // 保存源数据
        this.originalSendData = obj
        // 接收 其他组件发送来的  启停顺序
        this.data = {}
        this.showProcesses = []
        if (JSON.stringify(obj) === '{}') {
          this.status = 999
          return
        }
        setTimeout(() => {
          // 复制数据，阻隔操作源数据
          this.data = JSON.parse(JSON.stringify(obj))
          this.loadMainDevStatus()
        }, 100)
      }
    }
  }
</script>

<style scoped>
  .mainn{
    height: 100%;
    width: 100%;
  }
  .ddTitles{
    width: 15%;
    height: 100%;
    float: left;
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;
    border-right: solid 1px #eceeee;
  }

  .runBg {
    background: #0bff58;
  }

  .stayBg {
    background: #f1e9d8;
  }

  .errorBg {
    background: #f36a5a;
  }
  .defaultBg {
    background: rgba(243, 106, 90, 0);
  }
  .dxxxs {
    height: 63%;
    width: 100%;
    padding: 15px 3px;
    text-align: center;
  }
  .dxxxsy {
    height: 35%;
    width: 100%;
    padding: 3px;
    text-align: center;
  }
/*sdfsdfsd*/
  .chainn{
    width: 85%;
    float: left;
    padding: 25px 5px 25px 40px;
  }
  .ddfd {
    position: relative;
    height: 100%;
    width: 100%;
  }
</style>
